package com.zsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.constant.IdentityConstant;
import com.zsc.constant.JwtClaimsConstant;
import com.zsc.constant.MessageConstant;
import com.zsc.context.BaseContext;
import com.zsc.dto.ResetPasswordDTO;
import com.zsc.dto.UserLoginDTO;
import com.zsc.dto.UserPageQueryDTO;
import com.zsc.entity.User;
import com.zsc.exception.AccountNotFoundException;
import com.zsc.exception.PasswordEditFailedException;
import com.zsc.exception.PasswordErrorException;
import com.zsc.exception.PasswordIntErroy;
import com.zsc.mapper.UserMapper;
import com.zsc.properties.JwtProperties;
import com.zsc.result.PageResult;
import com.zsc.service.UserService;
import com.zsc.utils.JwtUtil;
import com.zsc.vo.UserLoginVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author cjr165123050
 * @description 针对表【user(员工信息)】的数据库操作Service实现
 * @createDate 2024-05-19 10:52:05
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {

        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(StringUtils.isNotBlank(userLoginDTO.getUsername()),
                User::getUsername, userLoginDTO.getUsername());
        User user = this.getOne(userLambdaQueryWrapper);
        if (Objects.isNull(user)) {
            throw new AccountNotFoundException("登录失败，没有该用户");
        }
        if (!user.getPassword().equals(userLoginDTO.getPassword())) {
            throw new PasswordErrorException("密码错误！！！！");
        }

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        String token = null;
        if (Objects.equals(user.getIdentity(), IdentityConstant.ADMIN)) {
            claims.put(JwtClaimsConstant.ADMIN_ID, user.getId());
            token = JwtUtil.createJWT(
                    jwtProperties.getAdminSecretKey(),
                    jwtProperties.getAdminTtl(),
                    claims);
        } else if (Objects.equals(user.getIdentity(), IdentityConstant.USER)) {
            claims.put(JwtClaimsConstant.USER_ID, user.getId());
            token = JwtUtil.createJWT(
                    jwtProperties.getUserSecretKey(),
                    jwtProperties.getUserTtl(),
                    claims);
        }

        UserLoginVO build = UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .identity(user.getIdentity())
                .token(token)
                .build();
        return build;
    }

    @Override
    public PageResult pageQuery(UserPageQueryDTO userPageQueryDTO) {
        // 创建分页对象
        Page<User> page = new Page<>(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());
        // 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userPageQueryDTO.getUsername() != null && !userPageQueryDTO.getUsername().isEmpty()) {
            queryWrapper.like("username", userPageQueryDTO.getUsername());
        }
        // 执行分页查询
        Page<User> userPage = this.page(page, queryWrapper);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();
        queryWrapper.orderByDesc("update_time");
        return new PageResult(total, records);

    }

    /**
     * 用户端 重置密码
     *
     * @param resetPasswordDTO
     */
    @Override
    public void resetPassword(ResetPasswordDTO resetPasswordDTO) {

        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);
        // 验证旧密码是否正确
        if (!user.getPassword().equals(resetPasswordDTO.getOldPassword())) {
            throw new PasswordIntErroy(MessageConstant.PASSWORD_ISERROY);
        }

        // 验证新密码与旧密码是否一致
        if (user.getPassword().equals(resetPasswordDTO.getPassword())) {
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_REPEAT);
        }

        // 验证新密码和确认密码是否一致
        if (!resetPasswordDTO.getPassword().equals(resetPasswordDTO.getPasswordRepeat())) {
            throw new PasswordErrorException(MessageConstant.CONFIRM_PASSWORD_IS_ERROR);
        }

        // 更新密码
        user.setPassword(resetPasswordDTO.getPassword());
        userMapper.updateById(user);
    }


}




